from flask_shop.category import category_bp,category_api,attr_api,attr_bp
from flask_shop import db,models
from flask_restful import Resource,reqparse,request

Category = models.Category

class Categorys(Resource):
    def get(self):
        try:
            level = request.args.get('level')
            pnum = request.args.get('pnum')
            psize = request.args.get('psize')
            if level:
                level = int(level)
            else:
                level = 3
            base_query = Category.query.filter(Category.level == 1)
            if all([pnum,psize]):
                cate_list = base_query.paginate(page=int(pnum),per_page=int(psize))
            else:
                cate_list = base_query.all()
            categoryList = self.to_tree(cate_list,level)
            return {'status':200,'msg':'获取成功','data':categoryList}
        except Exception as e:
            print(e)
            return {'status':400,'msg':'获取失败'}
        
    def to_tree(self,info:list,level:int):
        info_list = []
        for i in info:
            i_dict = i.to_dict()
            if i.level < level:
                i_dict['children'] = self.to_tree(i.children,level)
            info_list.append(i_dict)
        return info_list
    
    def post(self):
         try:
            name = request.get_json().get('name')
            level = request.get_json().get('level')
            pid = request.get_json().get('pid')

            if pid:
                c = models.Category(name=name,level=level,pid=pid)
            else:
                c = models.Category(name=name,level=level)
            # 保存到数据库
            db.session.add(c)
            db.session.commit()
            return {'status':200,'msg':'添加分类成功'}
         except Exception as e:
            print(e)
            return {'status':500,'msg':'添加分类失败'}
       

category_api.add_resource(Categorys,'/class_Category/')


class Attributes(Resource):
    def get(self):
         #创建一个Parser对象
            parser = reqparse.RequestParser()
            parser.add_argument('cid',type=int,required=True,location='args')
            parser.add_argument('_type',type=str,required=True,location='args')
            args = parser.parse_args()
            type = args.get('_type')
            #根据id获取分类信息，包括所有的属性
            cate = models.Category.query.get(args.get('cid'))
            attr_list = []
            if type == 'static':
                attr_list = [a.to_dict() for a in cate.attrs if a._type=='static']
            elif type == 'dynamic':
                attr_list = [a.to_dict() for a in cate.attrs if a._type=='dynamic']
            return {'status':200,'msg':'查询属性成功','data':attr_list}

    def post(self):
        try:
            #创建一个Parser对象
            parser = reqparse.RequestParser()
            parser.add_argument('name',type=str,required=True)
            parser.add_argument('value',type=str)
            parser.add_argument('_type',type=str,required=True)
            parser.add_argument('cid',type=int,required=True)
            #解析参数
            args = parser.parse_args()
            if args.get('value'):
                a = models.Attribute(name=args.get('name'),value=args.get('value'),_type=args.get('_type'),cid=args.get('cid'))
            else:
                a = models.Attribute(name=args.get('name'),_type=args.get('_type'),cid=args.get('cid'))
            db.session.add(a)
            db.session.commit()
            return {'status':200,'msg':'添加属性成功'}
        except Exception as e:
            print(e)
            return {'status':400,'msg':'添加属性失败'}


attr_api.add_resource(Attributes,'/class_attr/')

class Attribute(Resource):
    def get(self,id):
        attr = models.Attribute.query.get(id)
        return {'status':200,'msg':'获取属性成功','data':attr.to_dict()}
    def post(self,id):
        try:
            attr = models.Attribute.query.get(id)
            #创建一个Parser对象
            parser = reqparse.RequestParser()
            parser.add_argument('name',type=str)
            parser.add_argument('value',type=str)
            parser.add_argument('_type',type=str)
            parser.add_argument('cid',type=int)
            #解析参数
            args = parser.parse_args()
            name = args.get('name')
            typ = args.get('_type')
            value = args.get('value')
            cid = args.get('cid')
            if name:
                attr.name = name
            if value:
                attr.value = value
            if typ:
                attr._type = typ
            if cid:
                attr.cid = cid
            db.session.commit()
            return {'status':200,'msg':'修改属性成功'}
        except Exception as e:
            print(e)
            return {'status':400,'msg':'修改属性失败'}
        
    def delete(self,id):
        try:
            a = models.Attribute.query.get(id)
            if a:
                db.session.delete(a)
                db.session.commit()
                return {'status':200,'msg':'删除成功'}
            else:
                return {'status':400,'msg':'删除失败'}
        except Exception as e:
            return {'status':400,'msg':'删除失败'}



attr_api.add_resource(Attribute,'/single_attr/<int:id>/')